package com.zxing;

import java.io.IOException;
import java.util.Vector;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.snjp.hywaytools.R;
import com.zxing.camera.CameraManager;
import com.zxing.decoding.CaptureActivityHandler;
import com.zxing.decoding.InactivityTimer;
import com.zxing.view.ViewfinderView;
import android.app.Activity;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.SurfaceHolder.Callback;
import android.view.ViewGroup.LayoutParams;
import android.view.SurfaceView;
import android.view.Window;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class CaptureActivity extends Activity implements Callback,CaptureCallback{

	private CaptureActivityHandler handler;
	private ViewfinderView viewfinderView;
	private boolean hasSurface;
	private Vector<BarcodeFormat> decodeFormats;
	private String characterSet;
	private InactivityTimer inactivityTimer;
	private MediaPlayer mediaPlayer;
	private boolean playBeep;
	private static final float BEEP_VOLUME = 0.10f;
	private boolean vibrate;
	
	public RelativeLayout frame;
	public TextView camreaTitle;
	
	public WindowManager mWindowManager;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
//		setContentView(R.layout.scan_main);
		
		
	}
	
	public void showDialogCapture(){
		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		
		frame = (RelativeLayout) LayoutInflater.from(this).inflate(R.layout.scan_main, null);
		int width = metrics.widthPixels-30;
		Rect camreaRect = new Rect(0, 0, width, 500);
		CameraManager.init(getApplication(),camreaRect);
		viewfinderView = (ViewfinderView)frame. findViewById(R.id.viewfinder_view);
		hasSurface = false;
		inactivityTimer = new InactivityTimer(this);
		
		camreaTitle = (TextView)frame.findViewById(R.id.title);
		camreaTitle.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				closeCaptureDialog();
			}
		});
		
		SurfaceView surfaceView = (SurfaceView) frame.findViewById(R.id.preview_view);
		SurfaceHolder surfaceHolder = surfaceView.getHolder();
		if (hasSurface) {
			initCamera(surfaceHolder);
		} else {
			surfaceHolder.addCallback(this);
			surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		}
		decodeFormats = null;
		characterSet = null;
		
		mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
		WindowManager.LayoutParams layout_params_view = new WindowManager.LayoutParams(
				width, LayoutParams.WRAP_CONTENT,
				-1,
				WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
				PixelFormat.TRANSLUCENT);
		layout_params_view.gravity = Gravity.TOP | Gravity.LEFT;
		layout_params_view.x = 15;
		layout_params_view.y = metrics.heightPixels-550;
		mWindowManager.addView(frame, layout_params_view);
	}
	
	public void closeCaptureDialog(){
		try{
			if(frame.getVisibility() == View.VISIBLE && mWindowManager!=null){
				mWindowManager.removeView(frame);
				closeCamrea();
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
//		playBeep = true;
//		AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
//		if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
//			playBeep = false;
//		}
//		initBeepSound();
//		vibrate = true;
	}
	
	public void closeCamrea(){
		try{
			if (handler != null) {
				handler.quitSynchronously();
				handler = null;
			}
			CameraManager.get().closeDriver();
			inactivityTimer.shutdown();
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
//		if (handler != null) {
//			handler.quitSynchronously();
//			handler = null;
//		}
//		CameraManager.get().closeDriver();
	}

	@Override
	protected void onDestroy() {
//		inactivityTimer.shutdown();
		closeCaptureDialog();
		super.onDestroy();
	}

	private void initCamera(SurfaceHolder surfaceHolder) {
		try {
			CameraManager.get().openDriver(surfaceHolder);
		} catch (IOException ioe) {
			return;
		} catch (RuntimeException e) {
			return;
		}
		if (handler == null) {
			handler = new CaptureActivityHandler(this, decodeFormats,
					characterSet);
		}
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {

	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		if (!hasSurface) {
			hasSurface = true;
			initCamera(holder);
		}

	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		hasSurface = false;

	}

	public ViewfinderView getViewfinderView() {
		return viewfinderView;
	}

	public Handler getHandler() {
		return handler;
	}

	public void drawViewfinder() {
		viewfinderView.drawViewfinder();

	}

	public void handleDecode(Result obj, Bitmap barcode) {
//		closeCaptureDialog();
//		inactivityTimer.onActivity();
//		viewfinderView.drawResultBitmap(barcode);
//		 playBeepSoundAndVibrate();
		System.out.println("scanvalue:"+obj.getText());
//    	Intent intent = new Intent();
//    	intent.putExtra("scanvalue", obj.getText());
//    	setResult(Activity.RESULT_OK,intent);
//    	this.finish();
		handler.restartPreviewAndDecode();
	}

	private void initBeepSound() {
		if (playBeep && mediaPlayer == null) {
			// The volume on STREAM_SYSTEM is not adjustable, and users found it
			// too loud,
			// so we now play on the music stream.
			setVolumeControlStream(AudioManager.STREAM_MUSIC);
			mediaPlayer = new MediaPlayer();
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			mediaPlayer.setOnCompletionListener(beepListener);

			AssetFileDescriptor file = getResources().openRawResourceFd(
					R.raw.beep);
			try {
				mediaPlayer.setDataSource(file.getFileDescriptor(),
						file.getStartOffset(), file.getLength());
				file.close();
				mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
				mediaPlayer.prepare();
			} catch (IOException e) {
				mediaPlayer = null;
			}
		}
	}

	private static final long VIBRATE_DURATION = 200L;

	private void playBeepSoundAndVibrate() {
		if (playBeep && mediaPlayer != null) {
			mediaPlayer.start();
		}
		if (vibrate) {
			Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
			vibrator.vibrate(VIBRATE_DURATION);
		}
	}

	/**
	 * When the beep has finished playing, rewind to queue up another one.
	 */
	private final OnCompletionListener beepListener = new OnCompletionListener() {
		public void onCompletion(MediaPlayer mediaPlayer) {
			mediaPlayer.seekTo(0);
		}
	};

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		closeCaptureDialog();
	}
}